﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

using OTA.Notification.BO.Adapter;
using OTA.Notification.Entity.Adapter;

using OTA.Notification.BO.Dictionary;
using OTA.Notification.Entity.Dictionary;

using OTA.Notification.BO.Protocol;

using System.Collections.Generic;
using Strive.DataAccess.Base.Model.SearcherObject;
using OTA.Notification.Entity.Protocol;
using Strive.DataAccess.Base.Model.PageObject;

namespace OTA.Notification.Web.Adapter
{

    public class DetailAdapterBO : MsgAdapterConfigDetailBO
    {
        public DetailAdapterBO()
        {

        }

        protected override void ValidationRules()
        {
            //throw new NotImplementedException();
        }
    }

    public class AdapterBO : MsgAdapterConfigBO
    {
        public AdapterBO()
        {
            
        }

        protected override void ValidationRules()
        {
            //throw new NotImplementedException();
        }
    }

    public class ProtocolBO : MsgProtocolConfigBO
    {
        public ProtocolBO()
        {
            
        }

        protected override void ValidationRules()
        {
            //throw new NotImplementedException();
        }
    }

    public class ProtocolPropertiesBO : MsgProtocolPropertiesConfigBO
    {

        protected override void ValidationRules()
        {
            //throw new NotImplementedException();
        }
    }

    public partial class EditAdapter : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                InitPage();

                if (Request.QueryString["mscode"] != null && Request.QueryString["proto"] != null)
                {
                    //get info

                    Bind(Request.QueryString["mscode"], Request.QueryString["proto"]);
                }
            }
        }


        private void InitPage()
        {

            //类型加载

            using (DictionaryBO bo = new DictionaryBO())
            {

                IList<OTA_DICTIONARY> lstType = bo.getAllDictionary("Send", OTA.Notification.Common.DicType.Message, OTA.Notification.Common.LanguageType.Chinese);

                ddlType.Items.Insert(0, new ListItem("--发送类型--", ""));

                foreach (OTA_DICTIONARY dic in lstType)
                    ddlType.Items.Add(new ListItem(dic.NAME, dic.VALUE.ToString()));

            }

            using (ProtocolBO pbo = new ProtocolBO())
            {

                BasePageSearch bs = new BasePageSearch();

                bs.PageSize = 9999999;

                bs.PageIndex = 1;

                bs.Column = "*";

                PageResult<MsgProtocolConfigBean> lstProtocol = pbo.SelectPageList(bs);

                foreach (MsgProtocolConfigBean bean in lstProtocol.Data)
                    ddlProtocol.Items.Add(new ListItem(bean.ProtocolName, bean.ProtocolCode));

                ddlProtocol.Items.Insert(0, new ListItem("--通信协议--", ""));
            }

        }


        private void Bind(string MsgSendType, string ProtocolCode)
        {

            using (AdapterBO adap = new AdapterBO())
            {

                MsgAdapterConfigBean bean = adap.SelectByPK(MsgSendType, ProtocolCode);

                if (bean != null)
                {
                    txtName.Text = bean.AdapterName;

                    ddlType.SelectedValue = bean.MsgSendTypeCode;
                    ddlProtocol.SelectedValue = bean.ProtocolCode;

                    ddlType.Enabled = false;
                    ddlProtocol.Enabled = false;

                    if (bean.AsyncFlag.ToLower() == "t")
                        chkAsy.Checked = true;

                    //bind detail...

                    BindGrid(ddlProtocol.SelectedValue, true, MsgSendType);

                }
                else
                {
                    btnSave.Enabled = false;
                }
            }
        }


        protected void btnSave_Click(object sender, EventArgs e)
        {

            if (string.IsNullOrEmpty(ddlType.SelectedValue))
            {
                Response.Write("<script>alert('请选择发送类型！')</script>");
                return;
            }

            //if (string.IsNullOrEmpty(ddlProtocol.SelectedValue))
            //    return;

            if (string.IsNullOrEmpty(txtName.Text.Trim()))
            {
                Response.Write("<script>alert('请输入适配器名称！')</script>");
                return;
            }

            using (AdapterBO adap = new AdapterBO())
            {

                MsgAdapterConfigBean bean = new MsgAdapterConfigBean();


                #region Save adapter

                if (Request.QueryString["mscode"] != null && Request.QueryString["proto"] != null)
                {
                    //edit mode

                    bean = adap.SelectByPK(Request.QueryString["mscode"], Request.QueryString["proto"]);

                    adap.MarkOld();
                }
                else
                {

                    MsgAdapterConfigBean beanTest = new MsgAdapterConfigBean();

                    beanTest = adap.SelectByPK(ddlType.SelectedValue, ddlProtocol.SelectedValue);

                    if (beanTest != null)
                    {
                        //防止重复
                        Response.Write("<script>alert('适配器已存在！')</script>");

                        adap.Dispose();

                        return;
                    }

                    //new mode
                    bean.CreateTime = DateTime.Now;
                }

                bean.AdapterName = txtName.Text;


                if (chkAsy.Checked)
                    bean.AsyncFlag = "t";
                else
                    bean.AsyncFlag = "f";

                bean.ProtocolCode = ddlProtocol.SelectedValue;
                bean.MsgSendTypeCode = ddlType.SelectedValue;

                bean.LastUpdateTime = DateTime.Now;

                adap.Save(bean);

                #endregion

                #region save adapter detail


                using (DetailAdapterBO addBO = new DetailAdapterBO())
                {

                    addBO.DeleteAll(ddlType.SelectedValue, ddlProtocol.SelectedValue);

                    //insert new value

                    DataTable dt = GetDataTableFromPage();

                    foreach (DataRow dr in dt.Rows)
                    {
                        MsgAdapterConfigDetailBean obj = new MsgAdapterConfigDetailBean();

                        obj.MsgSendTypeCode = ddlType.SelectedValue;
                        obj.ProtocolCode = ddlProtocol.SelectedValue;
                        obj.ParamCode = dr["code"].ToString();
                        obj.ParamValue = dr["value"].ToString();


                        addBO.Save(obj);
                    }
                }

                #endregion

                //detail.ParamCode = "";

                //dbo.Save(detail);


            }

            Response.Write("<script>window.parent.Close()</script>");

        }

        private DataTable CreateDataTable()
        {
            DataTable dt = new DataTable();

            dt.Columns.Add("code");
            dt.Columns.Add("name");
            dt.Columns.Add("value");
            dt.Columns.Add("need");
            dt.Columns.Add("needflag");
            return dt;
        }

        private DataTable GetDataTableFromPage()
        {

            DataTable dt = CreateDataTable();

            int iIndex = 0;

            foreach (GridViewRow row in GridView1.Rows)
            {
                DataRow dr = dt.NewRow();

                string value = ((TextBox)row.Cells[1].FindControl("TextBox1")).Text;

                dr["value"] = value;

                dr["needflag"] = GridView1.DataKeys[iIndex]["needflag"];
                dr["code"] = GridView1.DataKeys[iIndex]["code"];

                dt.Rows.Add(dr);

                iIndex++;
            }

            return dt;
            
        }

        protected void ddlProtocol_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindGrid(ddlProtocol.SelectedValue, false, null);
        }

        private void BindGrid(string Protocol, bool ShowValue, string MsgSendType)
        {
            using (ProtocolPropertiesBO pbo = new ProtocolPropertiesBO())
            {
                BasePageSearch bs = new BasePageSearch();

                bs.PageSize = 9999999;

                bs.PageIndex = 1;
                bs.Column = "*";

                bs.Where = "AND PROTOCOL_CODE = '" + Protocol + "'";

                PageResult<MsgProtocolPropertiesConfigBean> lstProtocol = pbo.SelectPageList(bs);

                DataTable dt = CreateDataTable();

                using (DetailAdapterBO detailBO = new DetailAdapterBO())
                {
                    foreach (MsgProtocolPropertiesConfigBean bean in lstProtocol.Data)
                    {
                        DataRow dr = dt.NewRow();

                        dr["name"] = bean.ParamName;
                        dr["code"] = bean.ParamCode;

                        dr["needflag"] = bean.NeedFlag;

                        if (bean.NeedFlag.ToLower() == "t")
                            dr["need"] = "是";
                        else
                            dr["need"] = "否";

                        if (ShowValue)
                            dr["value"] = detailBO.getValue(MsgSendType, Protocol, bean.ParamCode);

                        dt.Rows.Add(dr);
                    }
                }

                GridView1.DataSource = dt;
                GridView1.DataBind();
            }
        }
    }
}
